package com.cpi.cornpp.sapfiles.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

import com.cpi.cornpp.common.exception.CornPPException;
import com.cpi.cornpp.common.files.exception.SAPComponentFileException;
import com.cpi.cornpp.recurrentcharges.exception.RecurrentChargesException;
import com.cpi.cornpp.sapfiles.form.SAPFileForm;
import com.cpi.cornpp.sapfiles.service.SAPFileService;
import com.cs.common.init.SystemParameterCollection;

public class SAPFileImporterAction extends MappingDispatchAction{
	
	
	private static final String DEFAULT = "default";	
	private static final String PATH_SAP_FILES_PARAM = "PATH_SAP_FILES";
	private static final String FILES_NUMBER = "FILES_NUMBER";

	/**
	 * Listar los archivos SAP
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws RecurrentChargesException
	 */
	public ActionForward list(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws SAPComponentFileException {
		SAPFileService service = null;
		List files = null;
		SAPFileForm form = null;
		
		try {
			service = new SAPFileService();
			form = (SAPFileForm)actionForm;
			files = service.list();
			form.setFiles(files);
			form.setPath(SystemParameterCollection.getInstance().getSystemParameterBean(PATH_SAP_FILES_PARAM).getValue());

			request.setAttribute(FILES_NUMBER, String.valueOf(files.size()));
		} catch (SAPComponentFileException exception) {

			SAPComponentFileException sapComponentFileException = null;
			exception.printStackTrace(System.out);
			sapComponentFileException= new SAPComponentFileException(exception , CornPPException.LAYER_ACTION,CornPPException.ACTION_UPDATE);
			throw sapComponentFileException;
		}
		
		return mapping.findForward(DEFAULT);
	}

	public ActionForward importFiles(ActionMapping mapping, ActionForm actionform, HttpServletRequest request, HttpServletResponse response) throws SAPComponentFileException {
		SAPFileService service = null;
		SAPFileForm form = null;
		try {
			service = new SAPFileService();
			form = (SAPFileForm)actionform;			
			service.importFiles(form.getFiles(), form.getSelectedFiles());
		} catch (SAPComponentFileException exception) {
			SAPComponentFileException SAPComponentFileException = null;
			exception.printStackTrace(System.out);
			SAPComponentFileException= new SAPComponentFileException(exception , CornPPException.LAYER_ACTION,CornPPException.ACTION_UPDATE);
			throw SAPComponentFileException;
		}
		request.setAttribute(FILES_NUMBER, String.valueOf(form.getFiles().size()));
		return mapping.findForward(DEFAULT);
	}
}
